import config

import MySQLdb
def getConnection():
    return MySQLdb.connect(host=config.databasehost, user=config.databaseuser, passwd=config.databasepasswd, db=config.databasename);
    
def streamingCursor(connection):
	return MySQLdb.cursors.SSCursor(connection)

def getCurScan(cursor):
	# keep track of the current scan number
	cursor.execute("select value from int_settings where name='curscan'")
	row=cursor.fetchone()
	if row:
		return int(row[0])
	return 0

def getNextScan(cursor):
	return (getCurScan(cursor)+1)%config.maxscans

def dotprogress():
	from sys import stdout
	print ".",
	stdout.flush()

def initTempTables(cursor):
	# initialize temporary tables
	cursor.execute("set @nextscan=%s",getNextScan(cursor))
	cursor.execute("create temporary table temp_file_stats (fileid int unsigned, filesize bigint unsigned)")
	cursor.execute("create temporary table temp_file_stats_single (fileid int unsigned, modified_date datetime)")
	cursor.execute("create temporary table temp_path_stats (pathid bigint unsigned, numsharedfiles int unsigned, totalsize bigint unsigned)")
	cursor.execute("create temporary table temp_host_stats (hostid mediumint unsigned, ip char(15), numsharedfiles int unsigned, totalsize bigint unsigned)")

def commitTempTables(cursor):
	print "Committing temp stats"

	try:
		cursor.execute("insert into host_stats (scanid, hostid, ip, numsharedfiles, totalsize) select @nextscan, hostid, INET_ATON(ip), numsharedfiles, totalsize from temp_host_stats");
		dotprogress()
		cursor.execute("update hosts,temp_host_stats set hosts.lastscan=@nextscan where hosts.id=temp_host_stats.hostid")
		dotprogress()

		cursor.execute("insert into path_stats (scanid, pathid, numsharedfiles, totalsize) select @nextscan, pathid, numsharedfiles, totalsize from temp_path_stats")
		dotprogress()
		cursor.execute("update paths,temp_path_stats set paths.lastscan=@nextscan where paths.id=temp_path_stats.pathid")
		dotprogress()

		cursor.execute("insert into file_stats (scanid, fileid, filesize) select @nextscan, fileid, filesize from temp_file_stats")
		dotprogress()
		cursor.execute("update files,temp_file_stats set files.lastscan=@nextscan where files.id=temp_file_stats.fileid")
		dotprogress()

		cursor.execute("insert into file_stats_single (fileid, modified_date) select fileid, modified_date from temp_file_stats_single on duplicate key update modified_date=values(modified_date)")
		dotprogress()
	except:
		print "Error while committing temp stats"
		raise

